首页 > 解决方案 > VUE 组件中的 Javascript 变量

问题描述

我在 index.html 中有 javascript 变量。例如 :

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="utf-8">
    <script>
        var testVariable = '111';
    </script>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>frontend</title>
    </head>
    <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
    </body>
    </html>

我打算testVariable在我的组件 vue 文件中使用。可能吗。这是我的helloworld.vue文件:

    <template >
    <div xmlns:th="http://www.thymeleaf.org" class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li><a href="https://vuejs.org" target="_blank">Core Docs</a></li>
      <li><a href="https://forum.vuejs.org" target="_blank">Forum</a></li>
      <li><a href="https://chat.vuejs.org" target="_blank">Community Chat</a></li>
      <li><a href="https://twitter.com/vuejs" target="_blank">Twitter</a></li>
      <br>
      <li><a href="http://vuejs-templates.github.io/webpack/" target="_blank">Docs for This Template</a></li>
    </ul>
    <h2>Ecosystem</h2>
    <ul>
     <span th:text="'Hello, ' + ${message}"></span>
      <li><a href="http://router.vuejs.org/" target="_blank">vue-router</a></li>
      <li><a href="http://vuex.vuejs.org/" target="_blank">vuex</a></li>
      <li><a href="http://vue-loader.vuejs.org/" target="_blank">vue-loader</a></li>
      <li><a href="https://github.com/vuejs/awesome-vue" target="_blank">awesome-vue</a></li>
    </ul>
    </div>
    </template>
    <script>
    export default {
    name: 'HelloWorld',
    data() {
    return {
      msg: 'Welcome to Your Vue.js App'
    };
    },
    };
     </script>

    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    h1, h2 {
      font-weight: normal;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>

我想在spring bootvuejs 中使用模型变量。需要发送此变量以进行进一步的axios标注。

标签: javascriptspring-bootvue.js

解决方案


您应该将所有纯 JavaScript 代码放入mounted函数中。

   export default {
      data() {
         return {
            msg: "some message"
         };
      },
      mounted: function (){
         // Your JavaScript code comes here in
      }
   };

推荐阅读