Vue Single-File Component (SFC):HTML、CSS、JavaScript都写在同一个.vue文件中,自包含
VUE特点:Declarative rendering
在data部分声明反应状态(reactive state),在本组件script中用this.xxx访问,可用于template中,比如,大括号中内容可以用js表达式{{ message }}
export default {data() {return {message: 'Hello World!'}}
}
{{}}只能用于文本的绑定,如果要绑定标签的属性,则用v-bind指令写法为,v-bind:id简写为:id
DOM事件监听用v-on指令,写法为,v-on:click可简写为@click,如示例中点击事件绑定了调用increment函数
v-bind和v-on一起我们可以对表单的input元素实现双向绑定,可简单用v-model指令(语法糖),v-model不仅用于input,也可以用于checkbox、radio button、select dropdown等
只有条件为true时才会被渲染,如下方示例awesome为true才会被渲染,否则被移除DOM,vue还支持v-else和v-else-if
Vue is awesome!
渲染列表时用v-for,示例中ttodos是在data中定义的一个列表,其中每个元素都有id和text属性
- {{ todo.text }}
更新列表的两种方式:
用computed选项声明从其他属性计算得到的属性,computed property会追踪它所依赖的反应式状态,缓存计算结果并在依赖发生改变时自动更新
export default {// ...computed: {filteredTodos() {// 实现,返回需要的对象}}
}
引用template中的元素可声明template refs,在template中用ref='nameforref'声明,声明后在script中可以用this.$refs.nameforref引用到这个元素,并可操作这个元素,前提是这个元素已经mounted了
hello
mounted时的回调函数定义可用mounted,这个是组件生命周期中的一个hook,还有created、updated
export default {mounted() {// component is now mounted.}
}
有时候想要做一些附加效果,需要监视某个属性的值,当其发生变化时做一些处理,示例中声明了count,并在watch中对其进行监视,函数名是这个变量的名字,参数是新的值,不要新的值可以无参数
export default {data() {return {count: 0}},watch: {count(newCount) {// yes, console.log() is a side effectconsole.log(`new count is: ${newCount}`)}}
}
使用组件需要先导入,即import xxx from xxx,并在components选项中声明被引用的子组件,在父组件的template中就可以用子组件的名字作为标签了,如
import ChildComp from './ChildComp.vue'export default {components: {ChildComp}
}
子组件暴露给父组件的用于接收父组件传值的输入,在子组件中用props选项声明,它可以直接在子组件中使用
// in child component
{{ msg || 'No props passed yet' }}
在父组件中通过v-bind指令传值,即:xxx,如下例所示greeting是父组件中声明的一个反应式状态,将其值传给子组件的msg
子组件可向父组件传emit事件,需要在emits选项中声明事件名字,this.emits()的第一个参数为事件名称,后面自定义其他传给事件的入参
export default {// declare emitted eventsemits: ['response'],created() {// emit with argumentthis.$emit('response', 'hello from child')}
}
父组件通过v-on监听子组件的emit事件
childMsg = msg" />{{ childMsg }}
除了通过props,父组件也可以通过slots向子组件传值,子组件中可以通过标签渲染从父组件传过来的内容,中的内容作为’fallback’内容,当父组件没有传任何值时显示fallback内容
Fallback content
父组件中
{{msg}}
vue说明文档:https://vuejs.org/guide/essentials/application.html