使用场景:需要在Vue中多次用到同一个表达式,表达式太长影响代码可读性且不方便放在data中
可以使用void 表达式,不会影响DOM
<template>
<div>
{{ void (value1 = 1, value2 = 2) }} // 不会渲染额外的 DOM
</div>
</template>
使用:set定义临时变量占位符,不能用在方法中
<div id="app">
<div
v-for="id in users"
:key="id"
:set="user = getUser(id)"
>
{{ user.name }}: {{ user.age }} years old
</div>
</div>
const app = new Vue({
el: '#app',
data: {
users: [1, 2, 3, 4],
usersData: {
1: {name: 'Mohamed', age: 29},
2: {name: 'Ahmed', age: 27},
3: {name: 'Zizo', age: 32},
4: {name: 'John', age: 13},
}
},
methods: {
getUser(id) {
return this.usersData[id];
},
},
});
举个例子:后台返回表格的数据中有一个字段是数组,要求默认只展示前三个,超过三个支持展开收起。效果如下:
代码如下:
<el-table ref="table">
<el-table-column label="文件名">
<template slot-scope="scope">
<div v-if="scope.row.fileLists && scope.row.fileLists.length">
{{ void (length = scope.row.fileLists.length) }}
<div
:style="
scope.row.isOverflow
? { height: '69px', overflow: 'hidden' }
: { height: 'auto' }
"
>
<p v-for="(item, index) in scope.row.fileLists" :key="item">
{{ item }}
<span v-if="index === length - 1">({{ length }})</span>
</p>
</div>
<el-button
v-if="length > 3"
type="text"
@click.prevent="scope.row.isOverflow = !scope.row.isOverflow; $refs.table.doLayout()"
>
{{ scope.row.isOverflow ? '展开全部' : '收起' }}
</el-button>
</div>
<p v-else>暂无文件</p>
</template>
</el-table-column>
</el-table>
参考链接:https://forum.vuejs.org/t/topic/30395/8,https://stackoverflow.com/questions/43999618/how-to-define-a-temporary-variable-in-vue-js-template
发表回复