vue技术分享之你可能不知道的7个秘密

2020-06-14 06:13:33易采站长站整理

}
}

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>

这样写很不精简,很多属性和事件都是手动定义的,我们可以如下写: