簡單的Vue元件構成
開始使用vue.js編寫前端代碼的時候,我們的了解一下.vue檔案的基本構成,不能說是.vue檔案,其實是一個元件,下面我們跟着代碼去了解一下吧。
<template>
<div class="hello">
</div>
</template>
<script>
import *** from ***;
export default {
props:{},
watch: {},
data: function(){
return{
}
},
//方法集
methods:{
},
created(){},
mounted(){}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
功能解釋
- 裡面寫的是html代碼
- 裡面寫的是js代碼
- import *** from ***; 代表的是導入某些元件和樣式
- export default 導出
//簡單介紹一下export,export default和export的差別和使用方法
1.export用于對外輸出本子產品(一個檔案可以了解為一個子產品)變量的接口
2.import用于在一個子產品中加載另一個含有export接口的子產品
示例:
//導出單個變量
export let name = "張三" (name.js)
//導入
import {name} from "./name.js"
export default {
...
}
//導出多個變量
let name1 = "張三";
let name2 = "李四";
export {name1,name2} (name.js)
//導入多個變量
import {name1,name2} from "./name.js"
export default {
data: function(){
return{
}
},
created:{
alert(name1+"say hello to"+name2)
}
}
//導出函數
function say(){
console.log("hello world");
}
export {say} (say.js)
//導入函數
import say from "./say.js"
export default {
data: function(){
return{
}
},
created:{
say(); //控制台列印hello world
}
}
3.export與export default均可用于導出常量、函數、檔案、子產品等,在一個檔案或子產品中;
export、import可以有多個,export default僅有一個;
通過export方式導出,在導入時要加{ },export default則不需要
示例:
//導出
let name = "胖子";
export dafault name;
//引入
import name from "./name.js"
其他的都類似,不做一一介紹
- created:html加載完成之前,執行。執行順序:父元件-子元件
- mounted:html加載完成後執行。執行順序:子元件-父元件
- methods:事件方法執行。
- watch:去監聽一個值的變化,然後執行相對應的函數。
- computed:computed是計算屬性,也就是依賴其它的屬性計算所得出最後的值
- props:接收父元件傳遞過來的參數
- 用來編寫css代碼