【问题标题】:vue.js – get new data informationvue.js – 获取新的数据信息
【发布时间】:2018-10-12 16:54:52
【问题描述】:

我正在使用 vue.js 构建一个 chrome 扩展。在我的一个 vue 组件中,我获取了当前选项卡的选项卡信息,并希望在我的模板中显示此信息。这是我的代码:

<template>
  <div>
    <p>{{ tab.url }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tab: {},
    };
  },
  created: function() {
    chrome.tabs.query({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, function(tabs) {
      this.tab = tabs[0];
    });
  },
};
</script>

问题是,模板在通过函数填充数据之前获取数据。什么是此问题的最佳解决方案,当标签数据在设置一次后不会改变。

我是否必须使用 watch 属性,尽管数据只更改一次?


// 已编辑:

我已经实施了解决方案,但它仍然不起作用。这是我的代码:

<template>
<div>
  <div v-if="tabInfo">
    <p>set time limit for:</p>
    <p>{{ tabInfo.url }}</p>
  </div>
  <div v-else> loading... </div>
</div>
</template>

<script>
export default {
  data() {
    return {
      tabInfo: null,
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      chrome.tabs.query({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, function(tabs) {
        console.log(tabs[0]);
        this.tabInfo = tabs[0];
      });
    },
  },
};
</script>

我的 getData 函数中的 console.log 语句将正确的对象写入控制台。但模板只显示 else 情况(正在加载...)。


// 编辑编辑

发现错误:我在回调函数中使用了“this”来引用我的数据,但回调函数中 this 的上下文是另一个上下文。

所以解决方法是使用

let self = this;

在回调函数之前并引用数据

self.tab

【问题讨论】:

    标签: vue.js google-chrome-extension vuejs2


    【解决方案1】:

    您可以将tab 初始化为null(而不是{})并在模板中使用v-if="tabs",类似于:

    // template
    <template>
      <div v-if="tab">
        <a href="tab.url">{{ tab.label }}</a>
        <p>{{ tab.body }}</p>
      </div>
    </template>
    
    // script
    data() {
      return {
        tab: null,
      }
    }
    

    new Vue({
      el: '#app',
      data() {
        return {
          tab: null, 
        }
      },
      mounted() {
        this.getData();
      },
      methods: {
        getData() {
          fetch('https://reqres.in/api/users/2?delay=1')
            .then(resp => resp.json())
            .then(user => this.tab = user.data)
            .catch(err => console.error(err));
        }
      }
    })
    <script src="https://unpkg.com/vue@2.5.17"></script>
    
    <div id="app">
      <div v-if="tab">
        <img :src="tab.avatar" width="200">
        <p>{{tab.first_name}} {{tab.last_name}}</p>
      </div>
      <div v-else>Loading...</div>
    </div>

    【讨论】:

    • 我真的很喜欢这个解决方案。谢谢!
    • @iamrobin。没问题:)
    • 我已经尝试过你的代码,但它仍然不起作用:(我已经用新代码编辑了我上面的帖子。你发现有什么错误吗?
    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 2011-10-06
    • 2012-10-31
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多