Vue学习笔记——vue组件

    技术2023-11-11  75

    1、Vue组件的基本使用步骤

    最原始的写法

    <div id="app"> <mycpn></mycpn> </div> <script> // 创建组件构造器对象 const mycpn = Vue.extend({ template:` <div> <h1>标题</h1> <p>段落</p> </div> `//反引号,Tab键上面的小点 }); // 注册组件 Vue.component('mycpn',mycpn); //Vue实例 const app = new Vue({ el:'#app' }); </script>

    步骤:创建组件对象 ⇒ 注册组件 ⇒ 使用组件,这样的组件为全局组件,可以在任意一个Vue实例中使用,下面这种注册方式

    <script> const app = new Vue({ el:'#app', components:{ mycpn } }); </script>

    就是局部组件,只能在这个app里使用,在其他地方无法使用

    组件模板分离写法

    <div id="app"> <cpn></cpn> </div> <template id="cpn"> <h1>{{message}}</h1> </template> <script> const cpn = { template:"#cpn", data(){ return{ message:"Hello Vue!!" } } } const app = new Vue({ el:"#app", components:{ cpn } }); </script>

    组件中同样也可以定义一些属性,比如data,methods等,要注意组件中的data要以函数的形式返回值

    2、组件之间通信

    父组件传给子组件,使用props

    <div id="app"> <cpn :childmessage="message" :childarr="parentArr"></cpn> </div> <template id="cpn"> <div> <h1>{{childmessage}}</h1> <h1>{{childarr}}</h1> <ul> <li v-for="item in childarr">{{item}}</li> </ul> </div> </template> <script> const cpn = { template: '#cpn', //props使用这种方式,可以设置类型和默认值 props: { childarr:{ type:Array,//传过来的是数组 default:[]//默认值为空数组 }, childmessage:{ type:String,//传过来的是字符串 default:""//默认值空字符串 } } } let app = new Vue({ el:'#app', data:{ message:'Hello!!', parentArr:['华为','三星','苹果'] }, components:{ cpn } }); </script>

    子组件传给父组件($emit)

    <div id="app"> <cpn @cclick="receiveData"></cpn> </div> <template id="cpn"> <div> <button @click="btnclick(index)" type="button" v-for="(item,index) in mobile">{{item.name}}</button> </div> </template> <script> const cpn = { template: "#cpn", data() { return { mobile: [{ id: "001", name: "华为" }, { id: "002", name: "苹果" }, { id: "003", name: "三星" }, { id: "004", name: "诺基亚" } ] } }, methods: { btnclick(index) { this.$emit("cclick", this.mobile[index]); } } } const app = new Vue({ el: "#app", components: { cpn }, methods: { receiveData(mobile) { console.log(mobile.name); } } }); </script>

    父组件访问子组件

    $children方法基本不怎么用,这里演示常用的$refs

    <div id="app"> <cpn ref="aaa"></cpn> <button type="button" @click="btnclick">click me!</button> </div> <template id="cpn"> <div> <h1>{{message}}</h1> </div> </template> <script> const cpn = { template:"#cpn", data(){ return{ message:"Hello Vue!!" } } } const app = new Vue({ el:"#app", data:{ message:"hhhh" }, components:{ cpn }, methods:{ btnclick(){ console.log("aaa:" + this.$refs.aaa.message); } } }); </script>

    子组件访问父组件

    <div id="app"> <cpn></cpn> </div> <template id="cpn"> <div> <h1>{{cmessage}}</h1> </div> </template> <script> const cpn = { template:"#cpn", data(){ return{ cmessage:this.$parent.message } } } const app = new Vue({ el:"#app", data:{ message:"Hello Vue!!" }, components:{ cpn } }); </script>

    另外,还可以用$root直接访问到根组件,用法跟上面的$parent差不多

    Processed: 0.018, SQL: 10