简体   繁体   English

如何绑定 html<title> vuejs 中的内容?</div></title><div id="text_translate"><p> 我正在尝试在 vuejs 上进行演示。 现在我想要 html 标题绑定一个 vm 字段。</p><p> 以下是我尝试过的:</p><p> index.html</p><pre> <.DOCTYPE html> <html id="html"> <head> <title>{{ hello }}</title> <script src="lib/requirejs/require.min.js" data-main="app"></script> </head> <body> {{ hello }} <input v-model="hello" title="hello" /> </body> </html></pre><p> app.js</p><pre> define([ 'jquery', 'vue' ], function ($, Vue) { var vm = new Vue({ el: 'html', data: { hello: 'Hello world' } }); });</pre><p> 但标题似乎没有限制,如何让它发挥作用?</p></div>

[英]How can I bind the html <title> content in vuejs?

I'm trying a demo on vuejs.我正在尝试在 vuejs 上进行演示。 Now I want the html title to bind a vm field.现在我想要 html 标题绑定一个 vm 字段。

The below is what I tried:以下是我尝试过的:

index.html

<!DOCTYPE html>
<html id="html">
<head>
    <title>{{ hello }}</title>
    <script src="lib/requirejs/require.min.js" data-main="app"></script>
</head>
<body>
{{ hello }}
<input v-model="hello" title="hello" />
</body>
</html>

app.js

define([
    'jquery', 'vue'
], function ($, Vue) {
    var vm = new Vue({
        el: 'html',
        data: {
            hello: 'Hello world'
        }
    });
});

But the title seemed not bounded, how to make it work?但标题似乎没有限制,如何让它发挥作用?

There are essentially two ways to solve it.基本上有两种方法可以解决它。

Use an existing Package使用现有包

For example, vue-meta :例如, vue-meta

 <template> <div id="app"> <router-view></router-view> </div> </template> <script> export default { name: 'App', metaInfo: { // if no subcomponents specify a metaInfo.title, this title will be used title: 'Default Title', // all titles will be injected into this template titleTemplate: '%s | My Awesome Webapp' } } </script>

Create your own Component创建自己的组件

Create a vue file containing:创建一个包含以下内容的 vue 文件:

<script>
    export default {
        name: 'vue-title',
        props: ['title'],
        watch: {
            title: {
                immediate: true,
                handler() {
                    document.title = this.title;
                }
            }
        },
        render () {
        },
    }
</script>

Register the component using使用注册组件

import titleComponent from './title.component.vue';
Vue.component('vue-title', titleComponent);

Then you can use it in your templates, eg然后你可以在你的模板中使用它,例如

<vue-title title="Static Title"></vue-title>
<vue-title :title="dynamic.something + ' - Static'"></vue-title>

You can do it with 1 line in the App.vue file, like this:您可以使用 App.vue 文件中的 1 行来完成,如下所示:

<script>
    export default {
        name: 'app',
        created () {
            document.title = "Look Ma!";
        }
    }
</script>

Or change the <title> tag content in public/index.html或者更改public/index.html<title>标签内容

<!DOCTYPE html>
<html>
  <head>
    <title>Look Ma!</title> <!- ------ Here ->
  </head>
...

This answer is for vue 1.x此答案适用于 vue 1.x

using requirejs.使用 requirejs。

 define([ 'https://cdn.jsdelivr.net/vue/latest/vue.js' ], function(Vue) { var vm = new Vue({ el: 'html', data: { hello: 'Hello world' } }); });
 <!DOCTYPE html> <html id="html"> <head> <title>{{ hello }}</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.js" data-main="app"></script> </head> <body> {{ hello }} <input v-model="hello" title="hello" /> </body> </html>

you can do it like this using the ready function to set the initial value and watch to update when the data changes.您可以使用 ready 函数来设置初始值并在数据更改时观察更新。

<html>
<head>
<title>Replace Me</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>

<div id="app">
  <input v-model="title">
</div>


<script>
new Vue({
    el: '#app',
    ready: function () {
        document.title = this.title
    },
    data: {
        title: 'My Title'
    },
    watch: {
        title: function (val, old) {
            document.title = val
        }
    }
})
</script>

</body>
</html>

also i tried this based on your original code and it works我也根据你的原始代码尝试了这个并且它有效

<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>

<div id="app">
  <input v-model="title">
</div>

<script>
new Vue({
    el: 'html',
    data: {
        title: 'My Title'
    }
})
</script>

</body>
</html>

Title and meta tags can be edited and updated asynchronously.标题和元标记可以异步编辑和更新。

You can use state management, create a store for SEO using vuex and update each part accordingly.您可以使用状态管理,使用 vuex 为 SEO 创建一个商店并相应地更新每个部分。

Or you can update the element by yourself easily或者您可以轻松地自己更新元素

created: function() {  

  ajax().then(function(data){
     document.title = data.title  
     document.head.querySelector('meta[name=description]').content = data.description
  })

}

Just to chime in here.只是想在这里插话。 I have read that VueJS wants nothing to do with the meta stuff so I would do such things outside of the "VueJS" realm.我已经读到 VueJS 不想与元数据有任何关系,所以我会在“VueJS”领域之外做这样的事情。

Basically make a plain vanilla js service like below.基本上制作一个简单的 vanilla js 服务,如下所示。 Here you could add all the functions to handle the meta data stuff such as the Open Graph data.在这里,您可以添加所有函数来处理元数据内容,例如 Open Graph 数据。

meta.js

export setTitle(title) {
    document.title = title  
}

Now we can import the service in main and then provide it to any component in the app who wants it.现在我们可以在 main 中导入服务,然后将其提供给应用程序中需要它的任何组件。 I could even use my meta service in other projects too which use different frameworks like React or Angular.我什至可以在其他使用 React 或 Angular 等不同框架的项目中使用我的meta服务。 Portability is super cool!便携性超爽!

main.js

import meta from './meta'
new Vue({
    router,
    render: h => h(App),
    provide: {
        meta: meta
    }
}).$mount('#app')

Here the component injects the meta service it wants to use.这里组件注入它想要使用的元服务。

someView.vue

export default {
    name: 'someView',
    inject: ['meta'],
    data: function() {
        returns {
            title: 'Cool title'
        }
    },
    created: function() {
        this.meta.setTitle(this.title);
    }
}

This way the meta service is decoupled from the app because different parent components can provide different versions of the meta service.这样元服务与应用程序分离,因为不同的父组件可以provide不同版本的meta服务。 Now you can implement various strategies to see which one is right for you or even different strategies per component.现在,您可以实施各种策略来查看哪种策略适合您,甚至每个组件都有不同的策略。

Basically the inject walks up the component hierarchy and takes the meta service from the first parent who provides it.基本上注入会沿着组件层次结构向上走,并从提供它的第一个父级获取meta服务。 As long as the meta service follows a proper interface, you're golden.只要元服务遵循适当的接口,您就是黄金。

Decoupling with DI is super cool 😃与 DI 解耦超酷😃

If you are using Vuex and want <title> to be part of your application state, then:如果您正在使用 Vuex 并希望<title>成为您应用程序状态的一部分,那么:

  • create a pageTitle state variable in Vuex在 Vuex 中创建一个pageTitle状态变量
  • map the state to the template using mapState()使用mapState()将状态映射到模板
  • watch it in template, probably add immediate: true to trigger the watcher right away在模板中watch它,可能添加immediate: true触发观察者
  • in watcher, document.title = pageTitle在观察者中, document.title = pageTitle

This will allow you to manage title with Vuex and keep them in sync.这将允许您使用 Vuex 管理标题并使它们保持同步。 I found it useful for SPAs.我发现它对 SPA 很有用。

By doing this you don't have to mess with your original HTML template, as most of the time Vue root template resides inside <body> .通过这样做,您不必弄乱原始 HTML 模板,因为大多数情况下 Vue 根模板位于<body>

This is for Vue 2.x.这适用于 Vue 2.x。

router.beforeEach((to, from, next) => {
  let mohican = to.path; if (mohican == '/') mohican = 'Home'
  document.title =  mohican.replace('/','');
  next();
 return;
});

I have an application toolbar component which is common for all pages of my SPA website and is nested in App.vue.我有一个应用程序工具栏组件,它对我的​​ SPA 网站的所有页面都是通用的,并且嵌套在 App.vue 中。 In every page I update my common toolbar title in the created hook of the page using Vuex store:在每个页面中,我使用 Vuex 商店在页面的创建挂钩中更新我的公共工具栏标题:

//in every page.vue
created() {
  this.$store.commit('toolBar', { pageTitle: this.pageTitle, ...  })
},

To automatically update the website title (along with the toolbar title) I use this mutation in the store:为了自动更新网站标题(以及工具栏标题),我在商店中使用了这个变化:

//store.js
toolBar(state,val){
  document.title = val.pageTitle
  state.toolBar = val
},

Similarly, I use the same mechanism to update eg SEO metadata同样,我使用相同的机制来更新例如 SEO 元数据

just pass只是通过

:title="data.name" :title="数据.名称"

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

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