如何在Vue.js中添加或应用全局变量
在Vue.js应用程序中,可能有一些数据或实用程序被多个组件使用,但您不想改变其作用域并保持其值对所有组件都相同。这些类型的变量被称为全局变量。 在这种情况下,用户可以使用以下语法定义原型-
Vue.prototype.$appName = 'My App'
现在这个 $appName
将在所有的Vue实例中都可用,甚至在创建之前。在appName之前定义的 $
是用于所有实例可用的属性的约定。用户还可以使用全局mixin来影响Vue实例。您可以将数据添加到这个mixin中,使一个或多个值对所有Vue组件可用。
请看下面的示例以获得更清楚的说明。
示例
首先,我们需要创建一个Vue项目。您可以参考这个页面来做到这一点。在您的Vue项目中创建两个文件app.js和index.html。下面为两个文件分别给出了包含代码片段的文件和目录。将下面的代码片段复制并粘贴到您的Vue项目中,并运行Vue项目。您将在浏览器窗口中看到如下输出。
- 文件名 – app.js
-
目录结构 — $project/public — app.js
// This is a global mixin, it is applied to every vue instance.
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
data: function() {
return {
get globalReadOnlyProperty() {
return "This property cannot be changed !";
}
}
}
})
Vue.component('child', {
template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});
new Vue({
el: '#app',
created: function() {
this.globalReadOnlyProperty = "I am a global read only Property";
}
});
-
文件名 – index.html
-
目录结构 — $project/public — index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div style="text-align: center;">
<h2>
Add or apply global variables in Vue.js
</h2>
</div>
<div id="app" style="text-align: center;">
In Root: {{globalReadOnlyProperty}}
<child></child>
</div>
<script src='app.js'></script>
</body>
</html>
运行以下命令以获取以下输出−
C://my-project/ > npm run serve
完整的HTML代码
现在让我们使用app.js和index.html文件创建一个完整的代码。这段代码可以作为一个HTML文件运行。
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div style="text-align: center;">
<h2>
Add or apply global variables in Vue.js
</h2>
</div>
<div id="app" style="text-align: center;">
In Root: {{globalReadOnlyProperty}}
<child></child>
</div>
<script>
// This is a global mixin, it is applied to every vue instance.
// Mixins must be instantiated *before* your call to new Vue(...)
Vue.mixin({
data: function() {
return {
get globalReadOnlyProperty() {
return "This property cannot be changed !";
}
}
}
})
Vue.component('child', {
template: "<div>In Child: {{globalReadOnlyProperty}}</div>"
});
new Vue({
el: '#app',
created: function() {
this.globalReadOnlyProperty = "I am a global read only Property";
}
});
</script>
</body>
</html>
在这篇文章中,我们讨论了全局变量以及如何在Vue.js中添加它们。我们创建了app.js和index.html文件,并使用<script>
标签将app.js文件添加到index.html文件中。最后,我们将app.js和index.html文件组合成一个完整的HTML文件。