Tim*_*rty 5 javascript vue.js vuejs2
这是我的代码:
<template>
<div>
<div v-html="data"></div> <button v-on:click="replace">Click Me to replace div contents</button>
</div>
</template>
<script>
export default {
data() {
return {
data: "I will be replaced once you click on button"
}
},
methods: {
clickMe() {
alert("worked");
},
replace(){
this.data = "Why does click me not work? It is loaded from server via ajax <a href v-on:click.prevent='clickMe'>Click Me</a>";
}
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
在这里,如果我单击Click Me to replace div contents内容将被替换,但是事件处理程序clickMe不会触发。这些数据将来自服务器,我需要编译该字符串并在Vue的上下文中使用它,以便Vue可以处理事件等。
如何从服务器上下载动态字符串?我正在使用Vue 2。
由于未编译v-html,因此您必须创建一个像这样的微型组件来解决该问题:
new Vue({
el: '#app',
data () {
return {
data: ``
}
},
computed: {
compiledData () {
return {
template: `<p>${this.data}</p>`
}
}
},
methods: {
replace () {
this.data = `Now click on me <a href='#' @click.prevent='alert("yo")'> here </a>`
}
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></script>
<div id="app">
<component :is="compiledData" ></component>
<button v-on:click="replace">Click Me to replace div contents</button>
</div>Run Code Online (Sandbox Code Playgroud)
上面的代码编译字符串内容,因此您可以按预期运行/执行函数
小智 5
使用 Vue 组件(codepen)的其他解决方案:
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div id="someId"></div> <button v-on:click="replace">Click Me to replace div contents</button>
<component :is="currentView"></component>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
currentView: null
},
methods:{
replace: function(){
var templateFromServer = getTemplate();
var comp=Vue.component('template-from-server', {
template: templateFromServer,
methods:{
clickMe:function (){
console.log("click");
}
}
});
this.currentView = comp;
}
}
});
function getTemplate(){
return "<a href v-on:click.prevent='clickMe'>Click Me</a>"
}
</script>
Run Code Online (Sandbox Code Playgroud)