<div>
<p>第一段</p>
<p>第二段</p>
</div>
`,
})
// 创建根实例
new Vue({
el: '#example'
})
</script>
Vue组件数据传递
一般地,我们在Vue实例对象或Vue组件对象中,我们通过data来传递数据
<div id="example">
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
</div>
<script>
// 注册
Vue.component('my-component', {
template: '<div>{{message}}</div>',
data:{
message: 'hello'
}
})
// 创建根实例
new Vue({
el: '#example'
})
</script>运行上面的代码,会使Vue停止执行,并在控制台发出错误提示,告诉你在组件中 data 必须是一个函数
可以用如下方式来绕开Vue的错误提示
<script>
// 注册
var data = {counter: 0}
Vue.component('my-component', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data:function(){
return data;
}
})
// 创建根实例
new Vue({
el: '#example'
})
</script>由于这三个组件共享了同一个 data,因此增加一个 counter 会影响所有组件
当一个组件被定义, data 需要声明为返回一个初始数据对象的函数,因为组件可能被用来创建多个实例。如果 data 仍然是一个纯粹的对象,则所有的实例将共享引用同一个数据对象。通过提供 data 函数,每次创建一个新实例后,能够调用 data 函数,从而返回初始数据的一个全新副本数据对象
因此,可以通过为每个组件返回全新的 data 对象来解决这个问题:
<script>
// 注册
Vue.component('my-component', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data:function(){
return {counter: 0};
}
})
// 创建根实例
new Vue({
el: '#example'
})
</script>现在每个 counter 都有它自己内部的状态了
Vue组件原生事件
有时候,可能想在某个组件的根元素上监听一个原生事件。直接使用v-bind指令是不生效的
<div id="example">
<my-component @click="doTheThing"></my-component>
<p>{{message}}</p>
</div>
<script>
Vue.component('my-component', {
template: '<button>按钮</button>',
})
new Vue({
el: '#example',
data:{
message:0
},
methods:{










