简体   繁体   English

在 VueJS 中的模板中显示值

[英]Show value in template in VueJS

I have some code below, I want show "header" in template and show or hide when header not null.我在下面有一些代码,我想在模板中显示“标题”,并在标题不为空时显示或隐藏。

<div id="hung">
    <cmx-test v-bind:header="${properties.header}"></cmx-test>
</div>
<script>
Vue.component('cmx-test', {
    props: ['header'],
        template: '<h1 class=\"fillColor\" data={{this.header}}></h1>'
});

// create a new Vue instance and mount it to our div element above with the id of app
var vm = new Vue({
  el: '#hung'
});

</script>

Your question is not totally clear.你的问题不是很清楚。 You have the component receiving the prop header but header is not defined on the main Vue instance.您有接收道具header的组件,但header未在主 Vue 实例上定义。 You need to be passing that prop from the main data object / Vue instance into the component to use it there.您需要将该道具从主数据对象/Vue 实例传递到组件中才能在那里使用它。

<div id="hung">
    <cmx-test v-if="header" :header="header"></cmx-test>
</div>

<script>
    Vue.component('cmx-test', {
        props: ['header'],
           template: '<h1 class=\"fillColor\" :data="header">{{header}}</h1>'
    });

    // create a new Vue instance and mount it to our div element above with the id of app
    var vm = new Vue({
      el: '#hung'
      data:{
         header: null,
      }
    });
</script>

Also using the same data object header to control whether the component is rendered or not using v-if .还使用相同的数据对象header控制是否使用v-if呈现组件。 So if header is null or false it wont be rendered.因此,如果header为 null 或 false,则不会呈现。 When it becomes true or contains a value it will be rendered and the value of header will be passed to component through binding it (eg :header="header")当它变为 true 或包含一个值时,它将被呈现并且header的值将通过绑定它传递给组件(例如:header="header")

There is some syntax mistake in your code, to insert text into tag you can achieve with v-text attribute not data={{this.header}} .您的代码中有一些语法错误,要将文本插入到标签中,您可以使用v-text属性而不是data={{this.header}}

And if you wanna hide some tag or component based on data value, you can use v-if .如果你想根据数据值隐藏一些标签或组件,你可以使用v-if

And the last thing is if you wanna pass value intro component you can achieve that with this way v-bind:header="value" , and value is variable which hold value you wanna pass.最后一件事是,如果您想传递值介绍组件,您可以通过这种方式实现v-bind:header="value" ,并且value是保存您想要传递的value的变量。

<div id="hung">
    <cmx-test v-if="header" v-bind:header="value"></cmx-test>
    <button @click="header = true">Display</button>
</div>
<script>
Vue.component('cmx-test', {
    props: ['header'],
    template: '<h1 class=\"fillColor\" v-text="header"></h1>'
});

// create a new Vue instance and mount it to our div element above with the id of app
var vm = new Vue({
  el: '#hung',
  data: {
    header: null,
    value: "Hello World!"
  }
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM