[英]vue.js render ajax data that contains vue.js syntax
Vue.js 版本為:2.x
你好。 我正在將 vue js 中的 ajax 請求發送到另一個頁面,並獲取它的源代碼,其中包含 vue.js 語法(例如事件)。 當此源添加到屬性和屬性添加到模板時,ajax 數據源(包含 vue.js 語法)無法呈現,無法正常工作。 例如模板是:
<div id="app">
{{{ foo }}}
</div>
app.js 是:
var app = new Vue({
el: '#app',
data: {
foo: 'bar'
},
mounted(){
this.$http.get('/media').then(function(response){
data = response.body;
Vue.set(app, 'foo', data);
});
},
methods: {
alertVideoLink: function(event){
alert(event.target.href);
}
}
});
在上面的 app.js 代碼中,ajax 請求返回這個代碼(即 response.body):
<a href="/media/videos" @click.pevent.self="alertVideoLink(event)">Video Link</a>
但此鏈接無法呈現且無法正常工作! 我正在測試渲染方法和一些有用的提示,但沒有找到。 請幫助...謝謝
聽起來您想使用Async Component 。
就像是...
components: {
'async-media': () => Vue.http.get('/media').then(res => ({
template: res.body,
methods: {
alertVideoLink (event) {
this.$emit('click', event)
}
}
}))
}
然后在您的模板中...
<async-media @click="handleClickEventFromChildComponent" />
這是一個使用超時來偽造“加載”模板的示例
var app = new Vue({ el: '#app', data: {}, components: { 'async-media': () => new Promise(resolve => { setTimeout(() => { resolve({ template: '<a href="/media/videos" @click.prevent.self="alertVideoLink($event)">Video Link</a>', methods: { alertVideoLink(event) { this.$emit('click', event.target.href) } } }) }, 2000) }) }, methods: { handleClickEventFromChildComponent (href) { console.info('Clicked on', href) } } });
<div id="app"> <p>Wait 2 seconds</p> <async-media @click="handleClickEventFromChildComponent" /> </div> <script src="https://unpkg.com/vue@2.4.2/dist/vue.min.js"></script>
@Phil 的回答是正確的,但在我的項目中需要更改。 在這種情況下,更好的方法是:使用全局組件與本地組件,因為這項工作很簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.