在Vue中,可以使用v-html指令来替代innerHTML来渲染数据,但是在这种情况下,渲染的内容不会执行组件中的脚本。因此,我们需要使用Vue的动态组件来解决这个问题。动态组件是Vue中一种高级技术,允许我们根据不同的条件选择不同的组件来加载。具体实现方法如下:
使用Vue的动态组件来渲染返回的HTML代码。在Vue中,动态组件使用component标记实现。首先,在模板中定义一个空的组件占位符,将要用来后续填充:
我们在这里使用了Vue的component标签,并动态指定其is属性,根据需要选择要显示的组件。我们还定义了一个currentComponent数据属性,用于跟踪当前渲染的组件。接下来,在获取AJAX响应时,将响应的HTML赋值给Vue组件中的一个数据属性。然后,在HTML响应被加载到Vue模板中的占位符中时,我们将currentComponent设置为具有该响应HTML的新组件。这将在Vue框架中自动执行所有脚本。
export default { data() { return { currentComponent: 'div', componentHtmlData: '' } }, created() { axios.get('/api') .then(response => { this.componentHtmlData = response.data; this.currentComponent = { template: this.componentHtmlData }; }) .catch(error => { console.log(error); }); } }
以上代码可用于Vue CLI项目