案例 1:
- 在子组件中两个按钮+1和-1,点击后修改count
- 整个操作的过程还是在子组件中完成,但是之后的展示交给父组件
- 这样,我们就需要将子组件中的count,传给父组件的某个属性,比如total
<!DOCTYPE html>
<html><head><script src&#61;"https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script src&#61;"https://unpkg.com/axios/dist/axios.min.js"></script>
</head><body><div id&#61;"app"><cpn &#64;deliver-count&#61;"receive"></cpn>父组件中的total:{{total}}</div><template id&#61;"counterCpn"><div><button &#64;click&#61;"incr">&#43;</button>{{count}} <button &#64;click&#61;"decr">-</button><button &#64;click&#61;"deliver">发送count给父组件中的total</button></div></template><script>const app &#61; new Vue({el: "#app",data: {total: 0,},methods: {receive(count) {this.total &#61; count;}},components: {cpn: {template: "#counterCpn",data() {return {count: 0,}},methods: {incr() {this.count&#43;&#43;;},decr() {this.count--;},deliver() {this.$emit(&#39;deliver-count&#39;, this.count)},},},},})</script>
</body></html>
案例2&#xff1a;
<!DOCTYPE html>
<html><head><script src&#61;"https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script src&#61;"https://unpkg.com/axios/dist/axios.min.js"></script>
</head><body><div id&#61;"app"><!-- cpnClick方法监听item-click自定义事件&#xff0c;不加括号&#xff0c;默认接收item-click内的参数 --><cpn &#64;item-click&#61;"cpnClick"></cpn></div><!-- 子组件模板 --><template id&#61;"cpn"><div><button v-for&#61;"(item,index) in categories" &#64;click&#61;"btnClick(item,index)">{{item.name}}</button></div></template><script>const cpn &#61; {template: "#cpn",data(){return{categories:[{id:&#39;aaa&#39;,name:&#39;热门推荐&#39;},{id:&#39;bbb&#39;,name:&#39;家用家电&#39;},{id:&#39;ccc&#39;,name:&#39;畅销手机&#39;},{id:&#39;ddd&#39;,name:&#39;好吃食品&#39;},]}},methods:{btnClick(item,index){this.$emit(&#39;item-click&#39;,item,index);}}}const app &#61; new Vue({el: "#app",data: {},methods: {cpnClick(item,index){console.log(&#39;cpnClick&#39;,item,index);}},components:{cpn,}})</script>
</body></html>