Vue组件基本格式,""内是组件在vue中使用的标签名,template内可以自定义组件内的标签,同时也能像vue一样使用methods和其他属性,但要使用vue中的methods需要用到props[]或者$emit
Vue.compontnt("",{
data() {
return {
count: 0
}
},
template: ""
})
props[]
在props[]内的同名变量,写在组件在vue的标签里,既可以直接赋值给该变量,也可以在前面加上冒号来获取vue中对应变量的值与对应属性的方法。
template内的@click="change" => props:["change"] => vue组件标签内:change => vue计算属性的方法 每一个都是相互对应的
<div id="app">
<div :style="{fontSize:size+'px'}">
<btn title="值" :change='changeSize'></btn>
</div>
</div>
<script>
Vue.component("btn", {
data() {
return {
count: 0
}
},
props: ["title","change"],//同名变量
methods: {
click() {
this.count++;
}
},
template: "<div><button @click='change'>{{count}}--{{title}}</button><a href='#'>123456</a></div>"
})
let vm = new Vue({
el: "#app",
data: {
msg:"父组件msg",
size:18
},
methods:{
changeSize(){
this.size+=4;
}
}
})
$emit
template内的$emit(\"change2\") => vue组件标签内@change2 => vue计算属性的方法
相对于props:[]比较简单同样也需要对应
<div id="app">
<div :style="{fontSize:size+'px'}">
<btn title="父组件传值" @change2="changeSize"></btn>
</div>
</div>
<script>
Vue.component("btn", {
data() {
return {
count: 0
}
},
methods: {
click() {
this.count++;
}
},
template: "<div><a href='#' @click.prevent='$emit(\"change2\")'>123456</a></div>"
})
let vm = new Vue({
el: "#app",
data: {
msg:"父组件msg",
size:18
},
methods:{
changeSize(){
this.size+=4;
}
}
})