Vue 构造选项

Vue 构造选项

Options

数据: data、props、methods、computed、watch

DOM:el、 template、render、renderError

生命周期钩子: created、mounted、updated、destroyed、beforeCreate、beforeMount、beforeUpdate、beforeDestroy、activated、deactivated、errorCaptured

资源:directives、components、filters

组合:mixins、extends、provide、inject、parent

其他

el挂载点

  • 类型:string | Element
  • 限制:只在用 new 创建实例时生效
  • 可以用$mount
new Vue({
  render:h=>h(App)
}).$mount('#app');

new Vue({
  el:'#app',
  render:h=>h(App)
});

data 内部数据

  • 类型:Object | Function
  • 限制:组件的定义只接受 function
  • 优先使用函数
函数
new Vue({   
  //data: function(){}
  data(){    
    return {
       n:0
    }
  }
})

对象
new Vue({    
  data:{ n:0 }
})

methods 方法

  • 类型:{ [key: string]: Function }
  • 注意,不应该使用箭头函数来定义 method 函数 (例如 plus: () => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined
<div>
  {{n}}
  <button @click="add">+1</button>
  {{filter()}}  
    // {{filter(array)}}
    // {{array.filter(i => i%2 === 0)}}  js数组filter方法
</div>

new Vue{
  data(){
    return{
      n:0,
      array:[1,2,3,4,5,6]
    },
  },
  methods:{
    add(){ 
      this.n += 1
    },
    filter(){
      return this.array.filter( i => i%2 === 0)
    }
    // filter(array){ array.filter( i => i%2 === 0) }
  }
}

components

  • 类型:Object
  • 详细:包含 Vue 实例可用组件的哈希表 Vue组件
  • 三种引入方式 : 推荐第一种
import Demo from './Demo.vue'
new Vue({
  components:{ Demo }  //{Demo:Demo}
})
<div>
  <Demo/>
</div>


Vue.component('Demo2',{
  template:`
    <div>demo2</div>
  `
})
<div>
  <Demo2/>
</div>


new Vue({
  components:{ 
     Demo3:{
       template: `<div>demo3</div>`
     }
  }
})
<div>
  <Demo3/>
</div>

Prop 外部数据

  • 也叫属性
  • message="n" 传入字符串
  • :message="n" 传入this.n数据
  • :fn="add" 传入this.add函数
Vue.component('Demo', {
  props: ['message','fn'],
  template:'
    {{ message }}
    <button @click="fn">call fn</button>
  '
})

new Vue({
  data:{
    n: 0
  },
  template:`
    <div>
      <Demo message="hello"/>
      <Demo :message="n" :fn="add"/>
    </div>
  `,
  methods:{
    add(){ this.n += 1 }
  }
})

Destroyed

 import Demo from './Demo.vue'  
 new Vue({
   components:{ Demo },  
   data:{ visible = true },
   template:`
    <div>
      <button @click="toggle">toggle</button>
      <hr>
      <Demo v-if="visible === true"/>
    </div>
   `,
   methods:{
      toggle(){
        this.visible = !this.visible 
      }
   }
 }).$mount('#app')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。