javascript - 如何将变量传递给 vue.js 模板中的函数?

标签 javascript html vue.js vuejs2 nuxt.js

我正在尝试使用 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”导致“事件” 等。这有可能吗,还是我找错了树?

最佳答案

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

<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>

关于javascript - 如何将变量传递给 vue.js 模板中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617933/

相关文章:

javascript - 如何创建一个不会在旧浏览器上导致错误的 ES6 模块?

javascript - Bootstrap - 客户评价 Carousel 问题

vue.js - 在 VueJs 中处理大数据

vue.js - 在计算中返回 getters 创建一个循环

javascript - 通过选择框创建实体

javascript - 段落内的 PHP Echo 不适用于所有记录

jquery - 前三个菜单工作正常,其他菜单无法使用

javascript - 如何根据点击事件显示Vue.js中嵌套对象的数据

javascript - 动态传递未知数量的参数来 react 路由器

javascript - ng-click 不适用于动态超链接