【问题标题】:How to pass variables to function inside of vue.js template?如何将变量传递给 vue.js 模板中的函数?
【发布时间】:2019-08-22 22:57:55
【问题描述】:

我正在尝试使用 Vue 中的模板组件将页面标题更改为页面标题。我试图通过将所有可能的页面标题存储在header-component 文件中的数组中来做到这一点。但是,当组件加载到页面上时,我找不到传入索引的方法。

这是有问题的组件:

<template id="comp-dem-template">
    <header-component>
        <!-- Insert replacement text in here-->
        <span slot="pagetitle">
            {{ chooseTitle(index) }}
        </span>
    </header-component>
</template>

<script>
module.exports = {
    template: '<h1><slot name="pagetitle">Page Title Fallback</slot></h1>',
    data: function chooseTitle(index) {
        if (index == 0){
            title: 'Index';
        }
        else if (index == 1){
            title: 'Events';
        }
        else if (index == 2){
            title: 'Policy';
        }
        else if (index == 3){
            title: 'Frequently Asked Questions';
        }
        else if (index == 4){
            title: 'Reservations';
        }
        else if (index == 5){
            title: 'View Reservations';
        }
        else{
            title: 'Make a Reservation';
        }
    }
}
</script>

<style>


</style>

以及组件从哪里加载

<template>
  <div class="container">
      <logo />
      <headercomponent />
      <navbar/>
  </div>
</template>

<script>
import Logo from '~/components/Logo.vue'
import headercomponent from '~/components/header-component.vue'
import navbar from '~/components/nav-bar.vue'
export default {
  components: {
    Logo,
    headercomponent,
    navbar
  }
}
</script>

<style>

</style>

我希望能够在我的索引页面的某处传递“0”,导致标题具有 “索引” 的文本,“1”导致 “事件” 等等。这甚至可能吗,还是我在吠叫错误的树?

【问题讨论】:

    标签: javascript html vue.js vuejs2 nuxt.js


    【解决方案1】:

    尝试将 index 声明为 headercomponent 中的道具,如下所示:

    <template id="comp-dem-template">
        <header-component>
            <!-- Insert replacement text in here-->
            <span slot="pagetitle">
                {{ title }}
            </span>
        </header-component>
    </template>
    
    <script>
    module.exports = {
     template: '<h1><slot name="pagetitle">Page Title Fallback</slot></h1>',
     props:['index'],
     data:  {
       if (this.index == 0) { //use this keyword
         title: 'Index';
       }
    ....
    

    并将其从父组件传递给子组件,例如:

    <template>
      <div class="container">
          <logo />
          <headercomponent index="0" />
          <navbar/>
      </div>
    </template>
    

    【讨论】:

    • 我可以很好地使用index 并显示索引道具,但是尝试执行{{chooseTitle()}} 或{{title}} 之类的操作,页面错误为“无法使用'in'运算符搜索索引中的“选择标题”。知道发生了什么吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 2020-10-23
    • 2019-10-03
    • 2017-11-10
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多