Vue 中的替代绑定语法.js问题上下文

2022-08-30 19:53:04

问题

我想知道是否有替代语法可以在Vue.js中输出数据,而不是像ng-bind Angular指令那样的大括号。

阅读文档,似乎Vue.js只接受带有v-bind指令的标签属性,但我希望它也与内部html一起使用。

上下文

我想使用PHP输出数据,一旦页面加载,就用Vue管理它。想象一下下下情况:

我们想要这个输出:

 <div>Hello</div> 

首先,我们使用php输出数据

 <div><?php echo $hello_string ?></div> 

之后,我们希望能够使用 Vue 更改内容。目前的语法是;

 <div>{{ hello_string }}</div> 

我们不能混合使用这两种语法,所以我需要这样的东西:

&lt!--Ideal syntax for mixing vue and php-->
<div v-bind:innerhtml="hello_string"><?php echo $hello_string ?></div> 

感谢您的帮助。


答案 1

您可以使用 v-text 指令:

<div v-text="hello_string"></div>
<!-- same as -->
<div>{{ hello_string }}</div>

v-html

<div v-html="html"></div>
<!-- same as -->
<div>{{{ html }}}</div>

答案 2
Vue.component({
    el:'#app',
    data:function(){
        return {
            hello_string:"<?php echo json_encode($hello_string) ?>"
        };
    }
});

然后在 HTML 中:

<div id="app><div>{{ hello_string }}</div></div>

基本上,你需要使用PHP来填充你的javascript变量,无论你是通过AJAX还是只是打印出上面的变量都取决于你。您可能需要将其编码为 JSON,或者至少确保对引号进行转义。在前端,让Vuejs管理视图,而不是使用PHP直接打印到视图中。