Vue.js 12个开发技巧和窍门
更漂亮的插槽语法
@click
表示 v-on:click
事件)或冒号表示方式用于绑定(:src
)。例如,如果你有一个表格组件,你可以使用这个功能如下:...
<my-table>
<template #row={ item }>
/* 一些内容,你可以在这里自由使用“item” */
template>
my-table>
...
template>
$on(‘hook:’) 可以帮助你简化代码
created
或 mounted
的钩子中定义自定义事件监听器或第三方插件,并且需要在 beforeDestroy
钩子中删除它以避免引起任何内存泄漏,那么这是一个很好的特性。下面是一个典型的设置:},
beforeDestroy () { window.removeEventListener('resize', this.resizeHandler);
}
$on('hook:')
方法,你可以仅使用一种生命周期方法(而不是两种)来定义/删除事件。window.addEventListener('resize', this.resizeHandler);
this.$on("hook:beforeDestroy", () => {
window.removeEventListener('resize', this.resizeHandler);
})
}
$on 还可以侦听子组件的生命周期钩子
使用 immediate: true 在初始化时触发watcher
title: (newTitle, oldTitle) => {
console.log("Title changed from " + oldTitle + " to " + newTitle)
}
}
handler(newVal, oldVal)
函数以及即时 immediate: true
的对象。title: {
immediate: true,
handler(newTitle, oldTitle) {
console.log("Title changed from " + oldTitle + " to " + newTitle)
}
}
}
你应该始终验证你的Prop
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
动态指令参数
...
<aButton @[someEvent]="handleSomeEvent()" />...
template>
<script>
...
data(){
return{
...
someEvent: someCondition ? "click" : "dbclick"
}
},
methods: {
handleSomeEvent(){
// handle some event
}
}
script>
重用相同路由的组件
{
path: "/a",
component: MyComponent
},
{
path: "/b",
component: MyComponent
},
];
router-view
组件中提供 :key
属性来实现。<router-view :key="$">router-view>
template>
把所有Props传到子组件很容易
<childComponent v-bind="$props" />
template>
<childComponent :prop1="prop1" :prop2="prop2" :prop="prop3" :prop4="prop4" ... />
template>
把所有事件监听传到子组件很容易
<div>
...
<childComponentv-on="$listeners" />...
<div>
template>
$createElement
$createElement
方法来创建和返回虚拟节点。例如,可以利用它在可以通过v-html指令传递的方法中使用标记。在函数组件中,可以将此方法作为渲染函数中的第一个参数进行访问。使用JSX
babel-plugin-transform-vue-jsx
获得JSX支持。自定义 v-model
v-model
是 @input
事件侦听器和 :value
属性上的语法糖。但是,你可以在你的Vue组件中指定一个模型属性来定义使用什么事件和value属性——非常棒!model: {
event: 'change',
prop: 'checked'
}
}
总结
THE END