我试图在vue上写一个方法,为什么' clickA'不能工作,但' clickB'可行?
注意:解决方案应该让throttle功能像' clickB'一样工作。
new Vue({
el: '#app',
methods: {
clickA: function() {
_.throttle(function() {
var date = new Date();
var time = date.toLocaleTimeString();
console.log('A clicked', time)
}, 1000)
},
clickB: _.throttle(function() {
var date = new Date();
var time = date.toLocaleTimeString();
console.log('B clicked', time)
}, 1000)
}
});

<script src="https://unpkg.com/vue@2.5.10/dist/vue.min.js"></script>
<script src="https://unpkg.com/lodash@4.17.4/lodash.min.js"></script>
<div id="app">
<button type="button" @click="clickA">A</button>
<button type="button" @click="clickB">B</button>
</div>
&#13;
答案 0 :(得分:1)
clickB
返回新功能。想想看,这可能有点难以理解,但这是有道理的!
_.throttle
绑定到clickA
返回的函数。
但是,在_.throttle
中,您并未将点击操作绑定到import React, { Component } from "react";
import { connect, Provider } from "react-redux";
import { Platform, BackHandler, View, Text } from "react-native";
import { Root, StyleProvider, StatusBar } from "native-base";
import { StackNavigator, NavigationActions } from "react-navigation";
import Drawer from "./Drawer";
import AuthNavigator from "./components/login/authNavigator";
import Home from "./components/home";
import Settings from "./components/settings";
import UserProfile from "./components/userProfile";
import getTheme from "../native-base-theme/components";
const AppNavigator = token => {
return StackNavigator(
{
Drawer: { screen: Drawer },
Login: { screen: Login },
Home: { screen: Home },
AuthNavigator: { screen: AuthNavigator },
UserProfile: { screen: UserProfile }
},
{
initialRouteName: token ? "Drawer" : "AuthNavigator",
stateName: "MainNav",
headerMode: "none"
}
);
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
isReady: false
};
}
componentDidMount() {
setTimeout(() => {
this.setState({ isReady: true });
}, 500);
}
render() {
let token = null;
const users = this.props.auth.users;
const index = this.props.auth.defaultUserIndex;
if (users.length > 0) {
token = users[index].token;
}
const Layout = AppNavigator(token);
return (
<Root>
<StyleProvider style={getTheme()}>{this.state.isReady ? <Layout /> : <View />}</StyleProvider>
</Root>
);
}
}
var mapStateToProps = state => {
return {
auth: state.auth
};
};
module.exports = connect(mapStateToProps)(App);
创建的该功能。
答案 1 :(得分:0)
_.throttle
返回一个限制函数。
所以你可以定义一个新函数:
var slowThing = _.throttle(fastThing)
或者您可以将函数定义为属性:
object: {
slowThing: _.throttle(fastThing)
}
但是在上面的clickA
中,限制功能尚未分配:
slowThing: function() {
// this creates a new function but doesn't execute it
_.throttle(fastThing)
}