1.本章摘要
在數(shù)據(jù)庫的某個(gè)字段中保存了一些布局樣式的信息,并且在某些標(biāo)簽中還含有click事件,動(dòng)態(tài)clss,style以及v-if,v-show等,如果我們直接只用v-html來展示數(shù)據(jù)的話,是能夠呈現(xiàn)給用戶的,但是缺少交互,添加的事件,變量都被當(dāng)做html元素的屬性處理了,故不能單純的使用v-html來完成帶有交互的后端字符排版文件。
那么具體怎么做呢?
>>> 積極嘗試一
1.官方文檔中有說到,渲染函數(shù)render,創(chuàng)建虛擬dom節(jié)點(diǎn),用一個(gè)組件去包裹,比如
Vue.component("anchored-heading", {
render(createElement, context){
// 完全透?jìng)魅魏翁匦浴⑹录O(jiān)聽器、子節(jié)點(diǎn)等。
return createElement('button', context.data, context.children)
},
props: {
msg: {
type: String,
default: "世界那么大"
}
},
methods: {
test() {
console.log("歡迎,你成功了");
}
}
});
但是像這種比較費(fèi)勁復(fù)雜,可以通過模板的形式做,如下
Vue.component("anchored-heading", {
template: `<div><span>{{ msg }}</span><button @click="test">測(cè)試用例</button</div>`,
props: {
msg: {
type: String,
default: "世界那么大"
}
},
methods: {
test() {
console.log("歡迎,你成功了");
}
}
});
還可以使用模板編譯,Vue.compile,使用該函數(shù)的前提是vuejs包含了該部分的代碼,為了縮小vuejs的體積,線上vuejs是不包含編譯的,如果要使用,就得使用包含編譯的代碼
import Vue from "vue";
let res = Vue.compile(
`<div><span>{{ msg }}</span><button @click="test">測(cè)試用例</button</div>`
);
Vue.component("anchored-heading", {
render: res.render,
props: {
msg: {
type: String,
default: "世界那么大"
}
},
methods: {
test() {
console.log("歡迎,你成功了");
}
}
});
Vue.compile返回的是一個(gè)對(duì)象,包含了staticRenderFns(數(shù)組),render(函數(shù))兩個(gè)值,render就是那個(gè)渲染函數(shù)
image.png
>>> 積極嘗試二
使用Vue.extend擴(kuò)展函數(shù),基于基礎(chǔ)Vue構(gòu)造器,創(chuàng)建一個(gè)"子類",參數(shù)一個(gè)包含組件選項(xiàng)的對(duì)象,要注意data選項(xiàng)是特例,必須是一個(gè)函數(shù),不是一個(gè)對(duì)象
<div id="mount-point"></div>
// 創(chuàng)建構(gòu)造器
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// 創(chuàng)建 Profile 實(shí)例,并掛載到一個(gè)元素上。
new Profile().$mount('#mount-point')
// 或者
let component = new Profile().$mount()
let dom = document.querySelector("#mount-point");
while (dom.hasChildNodes()) {
dom.removeChild(dom.firstChild);
}
dom.appendChild(component.$el);
結(jié)果如下
Walter White aka Heisenberg
如上就能夠解決v-html不能完全解決的問題啦!