1、.sync
修饰符
2.3.0+ 新增
vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。类似于v-model的效果
例子:
this.$emit('update:title', newTitle)
然后父组件可以监听那个事件并根据需要更新一个本地的数据属性
<text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event" ></text-document>
使用.sync
修饰符代替
<text-document v-bind:title.sync="doc.title"></text-document>
https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6
2、keep-alive
<keep-alive>是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。
<!-- 失活的组件将会被缓存!--> <keep-alive> <component v-bind:is="currentTabComponent"></component> </keep-alive>
https://cn.vuejs.org/v2/api/#keep-alive
3、异步组件
只在需要的时候才从服务器加载一个模块。Vue 允许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义
new Vue({ // ... components: { 'my-component': () => import('./my-async-component') } })
require.ensure()实现按需加载
4、处理边界情况
1.访问根实例:在每个 new Vue
实例的子组件中,其根实例可以通过 $root
属性进行访问
// 获取根组件的数据 this.$root.foo
很少用,应为一般使用Vuex 来管理应用的状态
2.访问子组件实例或子元素:通过 ref
特性为这个子组件赋予一个 ID 引用
<input ref="input">
methods: { // 用来从父级组件聚焦输入框 focus: function () { this.$refs.input.focus() } }
3.依赖注入:
实例选项:provide
和 inject
provide: function () { return { getMap: this.getMap } }
inject: ['getMap']
5、混入 (mixins)
混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。
// 定义一个混入对象 var myMixin = { created: function () { this.hello() }, methods: { hello: function () { console.log('hello from mixin!') } } } // 定义一个使用混入对象的组件 var Component = Vue.extend({ mixins: [myMixin] }) var component = new Component() // => "hello from mixin!"
https://cn.vuejs.org/v2/guide/mixins.html
6、Vue.set( target, key, value )向响应式对象中添加一个属性
-
参数:
{Object | Array} target
{string | number} key
{any} value
-
返回值:设置的值。
-
用法:
向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,因为 Vue 无法探测普通的新增属性 (比如
this.myObject.newProperty = 'hi'
)