<!DOCTYPE html>
<html> <head> <meta charset="UTF-8"> <title>Title of page</title> </head> <body> <div id="example"> <input v-model="parentsg"> <br> <child v-bind:parentsg="parentsg"></child> <!-- 直接绑定根数据text ,但是必须指明根数据的路径shou.text--> <todo-item v-bind:todo="todo"></todo-item> </div> <div id="counter-event-example"> <p>{ {childtofather}}</p> <p>{ { total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> <button-counter v-on:increment="incrementTotal"></button-counter> </div></body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script><script >// 注册Vue.component('child', { props: ['parentsg'], template: '<span>{ { parentsg}}</span>'})Vue.component('todo-item', { props: ['todo'], template: '<p>{ {todo.isComplete}}</p>'})// 创建根实例
new Vue({ el: '#example', data:{parentsg:'',
todo: { text: 'Learn Vue', isComplete: false }, shou: { text: 'shi wo ma', isComplete: false }}
})
Vue.component('button-counter', {
template: '<button v-on:click="incrementCounter">{ { counter }}</button>', data: function () { return { counter: 0 } },// 绑定了事件click————>increment
// 然后 this.counter += 1; this.$emit('increment1',this.counter);
// 这边就是触发事件 increment1,参考文献里面有点乱,这边是不是清晰多了
// 然后 <button-counter v-on:increment1="incrementTotal"></button-counter>
// v-on相当于监听吧,就触发 incrementTotal
// 传给父组件的参数 输出// this.counter
// 有没有很清晰,若有理解不对的地方,请指正
methods: { incrementCounter: function () { this.counter += 1 this.$emit('increment',this.counter) } },})new Vue({
el: '#counter-event-example', data: { total: 0, childtofather:'' }, methods: { incrementTotal: function (e) {this.total += 1;
//输出 this.counter console.log(e) // this.childtofather=e +"子传父传来的数据" } }})</script></html>