我正在尝试创建一个像v-if这样的自定义指令,因此它只会在传入元素的数据不为空的情况下呈现。例如:
<div v-if="!_.isEmpty(data.employer)">{{ data.employer.name }}</div>只有当data.employer不为空时才会呈现,这样就不会抛出引用错误。我正在尝试创建一个指令,将其简化为v-notEmpty="data.employer",并运行指令中的逻辑,但问题是,它在呈现元素后对自定义指令执行钩子,因此它抛出了雇主未定义的引用错误。
有没有办法让一个自定义指令完全像v-if一样工作,它在实际创建元素之前运行逻辑。这就是我到目前为止所得到的:
Vue.directive('notEmpty', (el, binding) => {
if (_.isEmpty(binding.value)) {
el.style.display = 'none';
} else {
el.style.display = 'initial';
}
});发布于 2017-09-13 13:19:32
你需要在绑定钩子函数中编写指令代码。(Reference)
绑定:
当指令第一次绑定到元素时,
只调用一次。这是您可以执行一次性设置工作的地方。
所以你的代码应该是:
Vue.directive('notEmpty', {
bind: function (el, binding, vnode) {
if (_.isEmpty(binding.value)) {
el.style.display = 'none';
} else {
el.style.display = 'initial';
}
}
});发布于 2018-10-09 03:54:56
一旦您使用Lodash,_.get()函数可能是一个更简单的解决方案。它提供了对嵌套对象属性的安全访问。一个简单的例子:
new Vue({
data: {
employer: {
name: {
first: 'Eric',
last: '',
},
age: 26
}
},
methods: {
/**
* Check if a property exists and returns a boolean
*
* @param {String} e Path to check
* @param {Object} o Object to be accessed
*
* @return {Boolean}
*/
notEmpty(o, e) {
let getResult = _.get(o, e);
return !(getResult == false || getResult == null || getResult == '' || getResult == undefined);
}
}
}).$mount('#app');<div id="app">
<p v-if="notEmpty(employer, 'name.first')">{{employer.name.first}}</p>
<p v-else>First name not informed</p>
<p v-if="notEmpty(employer, 'name.last')">{{employer.name.last}}</p>
<p v-else>Last name not informed</p>
<!-- Age will not appear, once is not defined -->
<p v-if="notEmpty(employer, 'age')">{{employer.age}}</p>
<p v-else>Age not informed</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script src="https://unpkg.com/vue@2.5.17/dist/vue.min.js"></script>
查看Lodash _.get()函数。这真是太棒了。
https://stackoverflow.com/questions/46165172
复制相似问题