Vue学习笔记 - 构造选项的基本属性

171 阅读2分钟

Vue构造选项

new Vue(options) 的 options

基本属性

1、el - 挂载点

替换掉目标元素 el: '#app'

也可用 vm.$mount('#app'),两者等价

2、data - 内部数据

  • 可以用对象
data:{
    n:0
}
  • 可以用函数
data(){
    return {
        n:0
    }
}

优先使用函数, 原因:避免多个实例共用了相同的data

3、methods - 方法

1、用作事件处理函数

2、用作普通函数,直接在 template 中调用,用{{ }}包裹

【小bug】:普通函数在template每次重渲染时均会被调用一次

4、components -- 组件

创建&使用组件

在 template 中引入另一个组件

有三种使用方法:

1、import 组件 【优先使用】

import Demo from './Demo.vue'
components: {
    Demo: Demo
}

然后在 template 中用<Demo/>标签引入

template:`
    <Demo/>
`

【注】:

  1. 文件名用小写
  2. 组件名(即Demo)用大写,防止与HTML标签重名
  3. 驼峰式的组件名在 template 中可用中划线式标签名,如组件名HelloWorld,在 template 中引用标签可写成<hello-world/>

2、全局的组件

Vue.component('Demo2', {
    同Vue构造选项options
})

然后在 template 中用标签引入

template:`
    <Demo2/>
`

3、1和2结合使用

components: {
    Demo3: {
        同Vue构造选项options
    }
}

在 template 中用标签引入

template:`
    <Demo3/>
`

插槽

使用组件时,组件可以有子元素,用到插槽。

组件 Demo 中,用 <slot /> 表示插槽内容:

<template>
	<div>
        <slot />
    </div>
</template>

使用组件,组件的子元素会替换掉<slot />

<Demo>
	<div>hello</div>
</Demo>

5、四个钩子

1、created(){}

实例/组件出现在内存后执行

2、mounted(){}

实例出现在页面后执行

3、updated(){}

实例更新后执行

4、destoryed(){}

实例从页面和内存消亡后执行

6、props - 外部数据(也叫属性)

从组件外部传入组件中的数据。

组件 Demo.vue 中:

props: ['x'] //props是一个数组

引入组件,同时传入数据 x 的值,在 template 中:

<Demo x="123"/> //传入字符串
<Demo :x="n"/> //传入this.n数据
<Demo :x="fn"/> //传入this.fn函数
<Demo :x="true"/> //传入其他JS数据类型