Vue2追加组件来编译包和访问商店数据

时间:2018-04-30 20:20:45

标签: javascript vuejs2 vuex

我希望我能说得对。我有一个已编译的Vue应用程序,我想在编译代码之外添加组件,这将是我的核心代码。我不希望任何人接触核心代码,但他们可以构建组件并访问vue组件内的存储数据。怎么能实现呢?

  1. 将组件附加到编译vue应用程序
  2. 访问组件内的vuex商店
  3. HTML index.html

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <h2>Essential Links</h2>
      </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>
    

    HelloWorld.vue

    let rockStars: [String: String?] = ["Sting": nil, "Elvis": "Presley", "Bono": nil, "Madonna": nil]
    
    let lastName = rockStars["Elvis"]
    print(lastName as Any)
    

1 个答案:

答案 0 :(得分:1)

您似乎希望允许普通用户访问商店状态,但不允许他们修改商店状态。

解决方案1:

您可能希望使用$refs然后调用该组件的方法来访问数据(或$ store.state)

解决方案2:

使用Vue Guide on Component Comunications等自定义事件。

代码如下:

&#13;
&#13;
Vue.config.productionTip = false

let componentOptions = {

  template: `<div>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <button @click="changeData()">Click me!!!</button>
  </div>
</div>`,
  data() {
    return {
      msg: 'Test'
    }
  },
  computed: {
    computedMsg: function () {
      return 'computed: ' + this.msg
    }
  },
  methods: {
    getData: function () {
      return this.computedMsg
    },
    changeData: function () {
      this.msg += '@'
      this.$emit('mymessage', 'computed: ' + this.msg)
    }
  }
}

Vue.component('child', componentOptions)

new Vue({
  el: '#app',
    data() {
      return {
        childMsg1: 'Welcome to Your Vue.js App',
        childMsg2: 'Welcome to Your Vue.js App'
      }
  },
  methods:{
    getChildData: function () {
      this.childMsg1 = this.$refs.test.getData()
    },
    getDataChangeForChild: function (data) {
      this.childMsg2 = data
    }
  }
})

let childBuilder = Vue.extend(componentOptions)
let yourChild = new childBuilder()
yourChild.$mount('#your-app')
function getData() {
  document.getElementById('your-app-data').innerText = yourChild.getData()
}
&#13;
.hello {
  background-color:gray
}
span {
  color:red;
}
&#13;
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>

<div id="app">
<h2>Case 1</h2>
  <button @click="getChildData()">Get Child Data</button>
  <p>Solution 1: {{childMsg1}}</p>
  <p>Solution 2: {{childMsg2}}</p>
  <child ref="test" v-on:mymessage="getDataChangeForChild"></child>
</div>
<h3 onclick="getData()">Case 2 (Click me to see the latest data): 
  <span id="your-app-data"></span>
</h3>
<div id="your-app"></div>
&#13;
&#13;
&#13;