批改状态:合格
老师批语:
组件:从形式上看就是一个自定义html标签
组件是可复用的vue实例,是构造函数vue的子类
<div id="root"><child-component></child-component></div><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script>//1.创建const childComponent =Vue.extend({template:`<h2>hello world</h2>`,});//2.注册// 使用 vue.component(组件名,是对象字面量表示的组件配置项)使用静态方式注册的称为 全局组件,全局组件声明在vue实例外部。通常一个项目只有一个vue实例,所以尽可能不要用全局组件//组件名:自定义的html标签Vue.component("child-component",childComponent);// 3.挂载const vm=new Vue({//挂载点:是隐式声明的组件el:'#root',//组件声明形式是中间用 -});</script>
局部组件只属于某个实例
<div id="root"><my-child></my-child></div><script>//局部组件只属于某个实例const vm=new Vue({el:"#root",//局部组件是属于vue实例的components:{//属性不用加双引号 my-child可以写成 myChild 不加双引号"my-child":{template:`<p>hello {{site}}</p>`,data(){return {site:"php中文网",}}}}});</script>
1.父组件向子组件传参
父组件是通过自定义属性的方式将参数传到子组件中
<div id="app"><!-- 绑定usernamew属性 --><btn-inc :usernamew="username"></btn-inc></div><script>const vm=new Vue({el:"#app",data(){return {username:"播放",}},//局部组件components:{btnInc:{//自定义属性props:['usernamew'],template:`<span>{{usernamew}}</span>`,},},}),</script>
2.子组件向父组件传参
子组件向父组件传参是通过同名事件来实现的
<btn-inc :usernamew="username" :my-count="count" @click-count="handle"></btn-inc><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script>const vm=new Vue({el:"#app",data(){return {username:"播放",count:0,}},//局部组件components:{btnInc:{//自定义属性props:['usernamew',"myCount"],//$emit(父组件中要使用的方法名称,子组件要传给父组件的值)template:`<div><button @click="$emit('click-count',10)>点赞:+{{myCount}}</button><span>{{usernamew}}</span></div>`,},},methods:{handle(value){this.count+=value;},},}),</script>
<div id="app"><p>父组件:{{price}}元</p><span>子主件</span><my-input :my-price="price" @input-text="handle"> </my-input></div><script>const vm=new Vue({el:"#app",data(){return{price:4567,};},//主件components:{"my-input":{props:['my-price'],template:`<input type="text" value="myPrice" @input="$emit('input-text',$event.target.value)" >`,methods:{handle(value){this.price=value;}},},},methods:{handle(value){this.price=value;}}});</script>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号