vuejs中的计算函数不适用于我

时间:2017-04-20 22:15:04

标签: vuejs2

我是vue.js的新手,有问题, 我有一个计算函数,提醒Word反转, 我使这个功能工作点击按钮,但它适用于页面加载,所以问题是什么。 这是vue.js代码,

function($text){
    $arr = [];
    $category = "";
    $subcategory = "";
    foreach (explode("\n", $text) as $line) {// For every line
        if (startsWith($line, '    ')){
            if (startsWith($line, '        ')) {
                // New Item
                // If it's a new item, you add it inside the current subcategory & category
                $arr[$category][$subcategory][] = substr($line, 8);// Removes the 8 spaces
            }
            else{
                // New Subcategory
                // If it's a new subcategory, you add it as an empty array inside the current category and set $subcategory to the current subcategory
                $subcategory = substr($line, 4);// Removes the 4 spaces
                $arr[$category][$subcategory] = [];
            }
        } else {
            // New Category
            // If it's a new category, you add it as an empty array and set $category to the current category
            $category = $line;
            $arr[$category] = [];
        }
    }
    return $arr;
}

这是HTML代码:

new Vue({
el: '#computed',
data: {
    word: 'welcome',
},
computed: {
    alertRev: function() {
        // get the word reversed
        alert (this.word.split('').reverse().join(''));
    },
}});

这是jsFiddle链接 Link to code

1 个答案:

答案 0 :(得分:1)

正如@BertEvans所指出的,一种方法将实现你想要做的。

我的理解是计算属性通常会返回函数的结果,而不是执行某个操作,例如警报。来自Vuejs docs(https://vuejs.org/v2/guide/computed.html)的无耻修改示例:

  CORRELATIONP3 <-CORRELATIONP2[product=='a',]

x<-CORRELATIONP3$b
y<-CORRELATIONP3$p


df <- data.frame(x = x)
m <- lm(y ~ x, data = df)
p <- ggplot(data = df, aes(x = x, y = y)) +
  scale_x_continuous("b (%)") +
  scale_y_continuous("p (%)")+
  geom_smooth(method = "lm", formula = y ~ x) +
  geom_point()
p

eq <- substitute(italic(r)~"="~rvalue*","~italic(p)~"="~pvalue, list(rvalue = sprintf("%.2f",sign(coef(m)[2])*sqrt(summary(m)$r.squared)), pvalue = format(summary(m)$coefficients[2,4], digits = 3)))


dftext <- data.frame(x = 30, y = 0.4, eq = as.character(as.expression(eq)))
p + geom_text(aes(label = eq), data = dftext, parse = TRUE)
new Vue({
  el: '#computed',
  data: {
    word: 'welcome',
  },
  computed: {
    reversedMessage: function() {
      // get the word reversed, no alert
      return this.word.split('').reverse().join('');
    },
  }
});

方法示例:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="computed" style="font-family: arial;">
  Type the word: <input type="text" v-model="word">
  <br />
  <br /> Reversed: {{ reversedMessage }}
</div>
new Vue({
  el: '#computed',
  data: {
    word: 'welcome',
  },
  methods: {
    alertRev: function() {
      // get the word reversed
      alert(this.word.split('').reverse().join(''));
    },
  }
});

另外,对于异步操作,计算属性不是很方便。

希望这并不强调你可以用湿拖把在邮票背面写下我对Vuejs的了解。