Home > Back-end >  Send data to a placeholder in Vue
Send data to a placeholder in Vue

Time:01-01

I want to display data from a list. Data in the list is updating inside a function. Actually I want to display the data only after execution of that function.

Here is my template code.

    <div >
          <td>{{shopName}}</td>
    </div>

And this is my script.

    <script>
    export default {
      name: "ViewShop",
      props:{
            shops:Object
        },
      data(){
        return{
          shopName:[],
        }
      },
      methods:{
        async shopd(sid){
          this.shopName=this.shops;
          console.log(this.shopName) // This prints the data in the console

        }
      }

    };
    </script>

I want to print the value of shopName in my template after executing the function shopd()

I think the shopName is accessed in template before executing the function. So what I need is it should wait until the function make some changes in shopName and then it should accessed to the template.

CodePudding user response:

For that you will need an auxiliary variable:

    <script>
    export default {
      name: "ViewShop",
      props:{
            shops:Object
        },
      data(){
        return{
          shopName:[],
          showShopName: false,
        }
      },
      methods:{
        async shopd(sid){
          this.shopName = this.shops;
          this.showShopName = true;
        }
      }

    };
    </script>

Then on your template:

    <div >
          <td>{{ showShopName ? shopName : "" }}</td>
    </div>

CodePudding user response:

You can use v-if directive. The html inside v-if will not be part of the dom until the v-if condition is met.

<div  v-if="shopName.length>0">
      <td>{{shopName}}</td>
</div>

Not sure if shopName is array or string the condition may change accordingly. And you can learn about conditional rendering from the documentation: https://vuejs.org/v2/guide/conditional.html

CodePudding user response:

Right now, I do not know if you need an array as the type or just a simple string. But in the template you can do this. If you change the type of the variable shopName to null and use the v-if directive to hide the element.

   <div  >
      <td v-if=shopName !== null>{{shopName}}</td>
   </div>

https://vuejs.org/v2/guide/conditional.html

  • Related