組件
- 每一個(gè)組件都是一個(gè)vue實(shí)例
- 每個(gè)組件均具有自身的模板template,根組件的模板就是掛載點(diǎn)
- 每個(gè)組件模板只能擁有一個(gè)根標(biāo)簽
- 子組件的數(shù)據(jù)具有作用域,以達(dá)到組件的復(fù)用
1、根組件
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script type="text/javascript">
// 通過new Vue創(chuàng)建的實(shí)例就是根組件(實(shí)例與組件一一對應(yīng),一個(gè)實(shí)例就是一個(gè)組件)
// 每個(gè)組件組件均擁有模板,template
var app = new Vue({
// 根組件的模板就是掛載點(diǎn)
el: "#app",
data : {
msg: "根組件"
},
// 模板: 由""包裹的html代碼塊,出現(xiàn)在組件的內(nèi)部,賦值給組件的$template變量
// 顯式書寫模塊,就會替換掛載點(diǎn),但根組件必須擁有掛載點(diǎn)
template: "<div>顯式模板</div>"
})
// app.$template
</script>
2、局部組件
<div id="app">
<local-tag></local-tag>
<local-tag></local-tag>
</div>
<script>
var localTag = {
data () {
return {
count: 0
}
},
template: '<button @click="btnAction">局部{{ count }}</button>',
methods: {
btnAction () {
this.count
}
}
}
new Vue({
el: "#app",
components: {
'local-tag': localTag
}
})
</script>
3、全局組件
<div id="app">
<global-tag></global-tag>
<global-tag></global-tag>
</div>
<script>
Vue.component('global-tag', {
data () {
return {
count: 0
}
},
template: '<button @click="btnAction">全局{{ count }}</button>',
methods: {
btnAction () {
this.count
}
}
})
new Vue({
el: "#app"
})
</script>
4、父組件傳遞數(shù)據(jù)給子組件
- 通過綁定屬性的方式進(jìn)行數(shù)據(jù)傳遞
<div id="app">
<global-tag :sup_data1='sup_data1' :supData2='sup_data2'></global-tag>
</div>
<script type="text/javascript">
Vue.component('global-tag', {
props:['sup_data1', 'supdata2'],
template: '<div>{{ sup_data1 }} {{ supdata2 }}</div>'
})
new Vue({
el: '#app',
data: {
sup_data1: '數(shù)據(jù)1',
sup_data2: '數(shù)據(jù)2'
}
})
</script>
5、子組件傳遞數(shù)據(jù)給父組件
- 通過發(fā)送事件請求的方式進(jìn)行數(shù)據(jù)傳遞
<div id="app">
<global-tag @send_action='receiveAction'></global-tag>
</div>
<script type="text/javascript">
Vue.component('global-tag', {
data () {
return {
sub_data1: "數(shù)據(jù)1",
sub_data2: '數(shù)據(jù)2'
}
},
template: '<div @click="clickAction">發(fā)生</div>',
methods: {
clickAction () {
this.$emit('send_action', this.sub_data1, this.sub_data2)
}
}
})
new Vue({
el: '#app',
methods: {
receiveAction (v1, v2) {
console.log(v1, v2)
}
}
})
</script>
6、父子組件實(shí)現(xiàn)todoList
<div id="app">
<div>
<input type="text" v-model="val">
<button type="button" @click="submitMsg">提交</button>
</div>
<ul>
<!-- <li v-for="(v, i) in list" :key="i" @click="removeMsg(i)">{{ v }}</li> -->
<todo-list v-for="(v, i) in list" :key="i" :v="v" :i="i" @delect_action="delect_action"></todo-list>
</ul>
</div>
<script type="text/javascript">
Vue.component("todo-list", {
template: "<li @click='delect_action'><span>第{{ i 1 }}條: </span><span>{{ v }}</span></li>",
props: ['v', 'i'],
methods: {
delect_action () {
this.$emit("delect_action", this.i)
}
}
})
new Vue({
el: "#app",
data: {
val: "",
list: []
},
methods: {
submitMsg () {
// 往list中添加input框中的value
if (this.val) {
this.list.push(this.val);
this.val = ""
}
},
delect_action(index) {
this.list.splice(index, 1)
}
}
})
</script>
來源:https://www./content-4-560001.html
|