gpt4 book ai didi

javascript - 如何在 vue 组件命名空间中定义可重用函数

转载 作者:搜寻专家 更新时间:2023-10-30 22:16:21 24 4
gpt4 key购买 nike

这是我的代码:

Vue.component("ro-webview", {
props: ["src"],
template: `<div>
<div>
<div class="col-md-2 list-inline">
${this.getIcon("fa-arrow-left")}
${this.getIcon("fa-arrow-right")}
${this.getIcon("fa-refresh")}
</div>
<input class="col-md-10" :value="src"/>
</div>
<iframe class="col-md-12" :src="src"/>
</div>`,

data: {
getIcon: function (iconName) {
return `<a class="btn btn-default" href="javascript:void(0)"><i class="fa ${iconName}" aria-hidden="true"></i></a>`
}
}
})

chrome 控制台提升

Uncaught TypeError: this.getIcon is not a function
(anonymous function)

定义getIcon会引起名称冲突,那么如何定义getIcon并使其只在我的组件中起作用?

最佳答案

您必须在 methods 中定义方法,如下所示:

    Vue.component("ro-webview", {
props: ["src"],
template: `<div> \
<div> \
<div class="col-md-2 list-inline"> \
<div v-html="getIcon('fa-arrow-left')" /> \
<div v-html="getIcon('fa-arrow-right')" /> \
<div v-html="getIcon('fa-refresh')" /> \
</div> \
<input class="col-md-10" :value="src"/> \
</div> \
<iframe class="col-md-12" :src="src"/> \
</div>`,
methods: {
getIcon: function (iconName) {
return "<a class='btn btn-default href='javascript:void(0)'><i class='fa " + iconName + " aria-hidden='true'></i></a>"
}
}
})

并且您不需要 this 来调用模板代码中的方法。

另请参阅 v-html 的用法.

查看工作 fiddle .

关于javascript - 如何在 vue 组件命名空间中定义可重用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41354730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com