Vuejs如何使用innerHtml改变元素内容
·
问题:Vuejs如何使用innerHtml改变元素内容
您好,我想知道单击按钮时如何更改<h3 id="score">``innerHtml。

在 Vanilla Javascript 中,我可以通过以下方式访问元素:
const score = document.querySelector('#score');
并通过这样做来改变它:
score.innerHtml = "13";
类似的东西。
<template>
<div id="scoreboard">
<h4>{{header_my}}</h4>
<button v-on:click="changeH3()">Change</button>
<h3 id="score">0</h3>
</div>
</template>
<script>
export default {
name: "scoreboard",
data() {
return {
header_my: "Hello Wolrd"
};
},
methods: {
changeH3() {
const h3 = document.querySelector("#score");
h3.innerHtml = "12";
}
}
};
</script>
当调用changeH3时,我该怎么做?h3的innerHtml和score的id必须改为12。
解答
使用 Vue.js 时不应直接操作 DOM。首先定义score数据属性。 Vue 知道您何时更改score并将进行 DOM 操作以更新视图。
new Vue({
el: "#scoreboard",
data() {
return {
header_my: "Hello Wolrd",
score: 0
};
},
methods: {
changeScore() {
this.score = 12;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="scoreboard">
<button @click="changeScore">Change</button>
<h3>{{ score }}</h3>
</div>
更多推荐




所有评论(0)