zoukankan      html  css  js  c++  java
  • Vue学习笔记-组件

    1.创建一个组件

    Vue.component('component',{
    
      template:`<div>这是一个组件</div> `,//直接写html,只能有一个根元素,即例子中的div不能有兄弟元素
    })

     

    2. 组件具有自己独立的作用域,即外部不能访问组件内部的变量,组件内部不能访问外部的变量。

        组件的data必须是函数,方法返回一个对象作为组件的data,看下例:

    Vue.component('component',{
    
      template:`<div>这是一个组件
                      <h1>{{message}}</h1>
                    </div> `,
    
      data(){
        return {
          message:"组件内部data"
       }
    } //返回对象
    
    })
    

      

    3,以上创建的都是全局组件,局部组件创建方法如下

    Vue.component('component',{
    
      template:`<div>这是一个组件
                      <h1>{{message}}</h1>
                      <hello></hello> //调用局部组件
                    </div> `,
    
      components: {
         hello: {
              template:`<div>hello</div>`,
         }
     
       },//局部组件只能当前组件中使用。
    
      data(){
        return {
          message:"组件内部data"
       }
    } //返回对象
    
    }) 

    4.父子组件传递数据

       父传子

    /*在父文件中调用子组件,并加上要传递的数据属性如下*/
      //父组件代码
     <hello v-bind:data="todos"></hello>   //hello为子组件,todos为你要传给子组件的数据,使用v-bind为动态绑定。
    
      //子组件代码
     Vue.component('hello', {
      props: ['data'],
      template: '<h3>{{ todos}}</h3>'
    })

    需要注意,在子组件中不能重新赋值父组件传递下来的数据,也就是父传子是单向的,这是为了防止子组件无意间更改父组件的状态。
    虽然引用类型的数据可以修改,但是不建议使用。

     子传父

     /*子组件代码*/
     在方法中写:
     this.$emit('name',value);   //name事件名称,value数据;
    
     /*父组件代码*/
     <hello v-on:name="method"> </hello>  
    //hello子组件,name自定义事件名称,method父组件处理子组件传来的value数据的方法。

      

  • 相关阅读:
    A physically based scene with three.js
    pbr-guide
    Art Pipeline for glTF
    GG5D
    Leetcode 146.LRU缓存机制
    Leetcode 143.重排链表
    Leetcode 142.环形链表II
    Leetcode 141.环形链表
    Leetcode 139.单词拆分
    Leetcode 138.复制带随机指针的链表
  • 原文地址:https://www.cnblogs.com/userGao/p/13094291.html
Copyright © 2011-2022 走看看