本文是 Vue 源码贡献值 Chris Fritz 在公共场合的一场分享,觉得分享里面有不少东西值得借鉴,虽然有些内容我在工作中也是这么做的,还是把大神的 ppt 在这里翻译一下,希望给朋友带来一些帮助。
这一点我在项目中也是这么写的。例如有请求需要再也没初始化的时候就执行一次,然后监听他的变化,很多人这么写:
- created(){
- this.fetchPostList()
- },
- watch: {
- searchInputValue(){
- this.fetchPostList()
- }
- }
上面的这种写法我们可以完全如下写:
- watch: {
- searchInputValue:{
- handler: 'fetchPostList',
- immediate: true
- }
- }
一般情况下,我们组件如下写:
- import BaseButton from './baseButton'
- import BaseIcon from './baseIcon'
- import BaseInput from './baseInput'
- export default {
- components: {
- BaseButton,
- BaseIcon,
- BaseInput
- }
- }
- <BaseInput v-model="searchText" @keydown.enter="search" />
- <BaseButton @click="search"> <BaseIcon name="search"/></BaseButton>
步骤一般有三部:
这也是最常见和通用的写法。但是这种写法经典归经典,好多组件,要引入多次,注册多次,感觉很烦。我们可以借助一下 webpack,使用 require.context() 方法来创建自己的(模块)上下文,从而实现自动动态 require 组件。
思路是:在 src 文件夹下面 main.js 中,借助 webpack 动态将需要的基础组件统统打包进来。
代码如下:
- import Vue from 'vue'
- import upperFirst from 'lodash/upperFirst'
- import camelCase from 'lodash/camelCase'
- // Require in a base component context
- const requireComponent = require.context(
- ‘./components’, false, /base-[\w-]+.vue$/
- )
- requireComponent.keys().forEach(fileName => {
- // Get component config
- const componentConfig = requireComponent(fileName)
- // Get PascalCase name of component
- const componentName = upperFirst(
- camelCase(fileName.replace(/^.//, '').replace(/.\w+$/, ''))
- )
- // Register component globally
- Vue.component(componentName, componentConfig.default || componentConfig)
- })
这样我们引入组件只需要第三步就可以了:
- <BaseInput
- v-model="searchText"
- @keydown.enter="search"
- />
- <BaseButton @click="search">
- <BaseIcon name="search"/>
- </BaseButton>
对于 vuex,我们输出 store 如下写:
- import auth from './modules/auth'
- import posts from './modules/posts'
- import comments from './modules/comments'
- // ...
- export default new Vuex.Store({
- modules: {
- auth,
- posts,
- comments,
- // ...
- }
- })
要引入好多 modules,然后再注册到 Vuex.Store 中,精简的做法和上面类似,也是运用 require.context() 读取文件,代码如下:
- import camelCase from 'lodash/camelCase'
- const requireModule = require.context('.', false, /\.js$/)
- const modules = {}
- requireModule.keys().forEach(fileName => {
- // Don't register this file as a Vuex module
- if (fileName === './index.js') return
- const moduleName = camelCase(
- fileName.replace(/(./|.js)/g, '')
- )
- modules[moduleName] = {
- namespaced: true,
- ...requireModule(fileName),
- }
- })
- export default modules
这样我们只需如下代码就可以了:
- import modules from './modules'
- export default new Vuex.Store({
- modules
- })
这一点,关于 vue 的引入,我之前在 vue 项目重构技术要点和总结中也提及过,可以通过 require 方式或者 import() 方式动态加载组件。
- {
- path: '/admin',
- name: 'admin-dashboard',
- component:require('@views/admin').default
- }
或者
- {
- path: '/admin',
- name: 'admin-dashboard',
- component:() => import('@views/admin')
- }
加载路由。
下面这个场景真的是伤透了很多程序员的心...先默认大家用的是 Vue-router 来实现路由的控制。 假设我们在写一个博客网站,需求是从 /post-haorooms/a,跳转到 /post-haorooms/b。
然后我们惊人的发现,页面跳转后数据竟然没更新?!原因是 vue-router 智能地发现这是同一个组件,然后它就决定要复用这个组件,所以你在 created 函数里写的方法压根就没执行。通常的解决方案是监听 $route 的变化来初始化数据,如下:
- data() {
- return {
- loading: false,
- error: null,
- post: null
- }
- },
- watch: {
- '$route': {
- handler: 'resetData',
- immediate: true
- }
- },
- methods: {
- resetData() {
- this.loading = false
- this.error = null
- this.post = null
- this.getPost(this.$route.params.id)
- },
- getPost(id){}
- }
bug 是解决了,可每次这么写也太不优雅了吧?秉持着能偷懒则偷懒的原则,我们希望代码这样写:
- data() {
- return {
- loading: false,
- error: null,
- post: null
- }
- },
- created () {
- this.getPost(this.$route.params.id)
- },
- methods () {
- getPost(postId) {
- // ...
- }
- }
解决方案:给 router-view 添加一个唯一的 key,这样即使是公用组件,只要 url 变化了,就一定会重新创建这个组件。
- <router-view :key="$route.fullpath"></router-view>
注:我个人的经验,这个一般应用在子路由里面,这样才可以不避免大量重绘,假设 app.vue 根目录添加这个属性,那么每次点击改变地址都会重绘,还是得不偿失的!
场景如下:
- (Emitted value instead of an instance of Error)
- Error compiling template:
- <div></div>
- <div></div>
- - Component template should contain exactly one root element.
- If you are using v-if on multiple elements, use v-else-if
- to chain them instead.
模板中 div 只能有一个,不能如上面那么平行2个 div。例如如下代码:
- <template>
- <li
- v-for="route in routes"
- :key="route.name"
- >
- <router-link :to="route">
- {{ route.title }}
- </router-link>
- </li>
- </template>
会报错!我们可以用 render 函数来渲染
- functional: true,
- render(h, { props }) {
- return props.routes.map(route =>
- <li key={route.name}>
- <router-link to={route}>
- {route.title}
- </router-link>
- </li>
- )
- }
当我们写组件的时候,通常我们都需要从父组件传递一系列的 props 到子组件,同时父组件监听子组件 emit 过来的一系列事件。举例子:
- //父组件 <BaseInput :value="value" label="密码" placeholder="请填写密码" @input="handleInput" @focus="handleFocus> </BaseInput> //子组件 <template> <label> {{ label }} <input :value="value" :placeholder="placeholder" @focus=$emit('focus', $event)" @input="$emit('input', $event.target.value)" > </label> </template>
这样写很不精简,很多属性和事件都是手动定义的,我们可以如下写:
- <input
- :value="value"
- v-bind="$attrs"
- v-on="listeners"
- >
- computed: {
- listeners() {
- return {
- ...this.$listeners,
- input: event =>
- this.$emit('input', event.target.value)
- }
- }
- }
$attrs 包含了父作用域中不作为 prop 被识别(且获取)的特性绑定(class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定,并且可以通过 v-bind="$attrs" 传入内部组件。
$listeners 包含了父作用域中的(不含 .native 修饰器的)v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件。